package com.intelligent.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component
public class RedisManagementUtils {

    private static final Logger logger = LoggerFactory.getLogger(RedisManagementUtils.class);

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    /**
     * 检查并修复Redis状态
     */
    public void checkAndFixRedisStatus() {
        try (RedisConnection connection = redisConnectionFactory.getConnection()) {
            String role = getRedisRole(connection);
            logger.info("Current Redis role: {}", role);
            
            if ("slave".equals(role)) {
                logger.warn("Redis is configured as slave, promoting to master...");
                promoteToMaster(connection);
                
                // 等待一段时间让Redis处理
                Thread.sleep(2000);
                
                // 再次检查状态
                String newRole = getRedisRole(connection);
                logger.info("Redis role after promotion: {}", newRole);
                
                if ("master".equals(newRole)) {
                    logger.info("Successfully promoted Redis to master");
                } else {
                    logger.warn("Redis role is still: {}", newRole);
                }
            } else if ("master".equals(role)) {
                logger.info("Redis is already configured as master");
            } else {
                logger.warn("Unknown Redis role: {}", role);
            }
        } catch (Exception e) {
            logger.error("Error checking/fixing Redis status: ", e);
            // 不抛出异常，让应用继续运行
            logger.warn("Continuing with current Redis configuration despite error");
        }
    }

    /**
     * 获取Redis实例的角色
     */
    private String getRedisRole(RedisConnection connection) {
        try {
            // 执行INFO replication命令获取复制信息
            java.util.Properties info = connection.info("replication");
            String role = info.getProperty("role");
            if ("master".equals(role)) {
                return "master";
            } else if ("slave".equals(role)) {
                return "slave";
            }
            return "unknown";
        } catch (Exception e) {
            logger.error("Error getting Redis role: ", e);
            return "error";
        }
    }

    /**
     * 将Redis副本提升为主节点
     */
    private void promoteToMaster(RedisConnection connection) {
        try {
            // 执行SLAVEOF NO ONE命令将副本提升为主节点
            connection.slaveOfNoOne();
            logger.info("Successfully promoted Redis instance to master");
            
            // 验证提升是否成功
            Thread.sleep(1000); // 等待1秒让Redis处理命令
            String newRole = getRedisRole(connection);
            logger.info("New Redis role after promotion: {}", newRole);
        } catch (Exception e) {
            logger.error("Error promoting Redis to master: ", e);
        }
    }

    /**
     * 测试Redis写操作
     */
    public boolean testRedisWrite() {
        try (RedisConnection connection = redisConnectionFactory.getConnection()) {
            String testKey = "test:write:" + System.currentTimeMillis();
            String testValue = "test_value";
            
            // 尝试写操作
            connection.set(testKey.getBytes(), testValue.getBytes());
            
            // 读取验证
            byte[] result = connection.get(testKey.getBytes());
            boolean success = testValue.equals(new String(result));
            
            // 清理测试数据
            connection.del(testKey.getBytes());
            
            logger.info("Redis write test result: {}", success);
            return success;
        } catch (Exception e) {
            logger.error("Redis write test failed: ", e);
            return false;
        }
    }
}